var book_id;
/*
*   getBook(id) was called when a file download success.
*   a variable's name allFile is a phonegap's local storage, it will store all of book which is dowloaded on device.
*/
function getBook(id, fullPath) {
    try {
        $.ajax({
            url: "http://phanhuutho.com/thesis/test?id=" + id,
            type: 'POST',
            dataType: 'json',
            error: function (data) {
                console.log("App launch error", data);
            },
            success: function (data) {
                alert("getBook success!!");
                data.fullPath = fullPath; 
                var localData = JSON.stringify(data);
                // localData.fullPath = fullPath;
                window.localStorage.setItem("book_" + id, localData);
                var getlocalData = JSON.parse(localStorage.getItem('book_'+id));
                // var localData = localStorage.getItem('book_'+id);
                // $.each(getlocalData, function(key, value){
                //     alert(key + ' = ' + value);
                // });
            }
        });
    } catch (err) {
        // err
    } 
}     
function downloadFile(id) {
    alert('hi');
    book_id = id;
    window.requestFileSystem(
        LocalFileSystem.PERSISTENT,
        0,
        onRequestFileSystemSuccess,
        fail
    );
}

function onRequestFileSystemSuccess(fileSystem) {
    alert('book_id '+ book_id);
    fileSystem.root.getFile(
        'dummy.html',
        {create: true, exclusive: false},
        onGetFileSuccess,
        fail
    );
}

function onGetFileSuccess(fileEntry) {
    alert('onGetFileSuccess! -->'+ book_id);
    var path = fileEntry.toURL().replace('dummy.html', '');
    var fileTransfer = new FileTransfer();
    fileEntry.remove();
    
    fileTransfer.download(
        'http://phanhuutho.com/thesis/epub/index/export-epub/id/'+ book_id,
        path + 'book_' + book_id + '.epub',
        function(file) {
            alert('download complete: ' + file.toURI());
            getBook(book_id, file.toURI());
            showLink(file.toURI());
        },
        function(error) {
            alert('download error source ' + error.source);
            alert('download error target ' + error.target);
            alert('upload error code: ' + error.code);
        }
    );
}

function showLink(url) {
    alert(url);
}
